def crc16_cal(datalist):

    test_crc=0xffff
    poly=0xa001

    numl = len(datalist)
    for num in range(numl):
        data = datalist[num]
        test_crc=(data&0xff)^test_crc

        for bit in range(8):

            if(test_crc&0x1) != 0:

                test_crc>>=1
                test_crc^=poly

            else:

                test_crc>>=1
    crc_val = hex(test_crc)
    first= crc_val[-2:]
    second= crc_val[2:4]

    return f"0x{first}{second}"

def pack_data(data: bytearray) ->bytearray: 

    '''
    data: 要效验的数据

    return: 效验完的数据， 末尾添加了crc值

    data = bytearray([0x01, 0x06, 0x00, 0x12, 0x00, 0x01])

    return  bytearray(b'\x01\x06\x00\x12\x00\x01\xe8\x0f')
    
    '''

    crc_val = crc16_cal(data)[2:]

    first= int("0x" + crc_val[:2], 16)
    second= int("0x" + crc_val[2:], 16)

    data.append(first)
    data.append(second)

    return data

if __name__ == "__main__":

    x = "c88300209d010108b3270108c5240108b1270108e102010849320108000000000000000000000000000000005d2c"

    data = bytearray([0xC8,0x83,0x00,0x20,0x9D,0x01,0x01,0x08,0xB3,0x27,0x01,0x08,0xC5,0x24,0x01,0x08,0xB1,0x27,0x01,0x08,0xE1,0x02,0x01,0x08,0x49,0x32,0x01,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5D,0x2C])

    data = b"\x06\x03\x00\xdc\x00\x01@\xc8\x83\x00 \x9d\x01\x01\x08\xb3\'\x01\x08\xc5$\x01\x08\xb1\'\x01\x08\xe1\x02\x01\x08I2\x01\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00],\x01\x08\xfd\x02\x01\x08\x00\x00\x00\x00\xb7\'\x01\x08_,\x01\x08"

    # data = bytearray([0x01, 0x06, 0x00, 0x14, 0x17, 0x01])

    # x = pack_data(data)

    x = crc16_cal(data)
    # # x = checksum(data)

    print(x)